import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:net/http/dao/account_dao.dart';
import 'package:net/navigator/hi_navigator.dart';
import 'package:hi_base/empty.dart';
import 'package:hi_base/toast.dart';
import 'package:net/widget/appbar.dart';
import 'package:net/widget/login_btn.dart';
import 'package:net/widget/login_effect.dart';
import 'package:net/widget/login_input.dart';

class HLogin extends HookWidget {
  const HLogin({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ValueNotifier<bool> protect = useState(false); //是否密码可见
    ValueNotifier<bool> loginEnable = useState(false); //是否登录按钮置灰
    ValueNotifier<Map<String, dynamic>> data = useState({
      'userName': '',
      'password': '',
    });

    void checkInput() {
      if (isNotEmpty(data.value['userName']) &&
          isNotEmpty(data.value['password'])) {
        loginEnable.value = true;
      } else {
        loginEnable.value = false;
      }
    }

    void send() async {
      try {
        var result = await LoginDao.login(
            data.value['userName'], data.value['password']);
        // result['code'] == 200这是我自己mock的
        print(result);
        if (result['code'] == 0) {
          showToast('登录成功');
          HiNavigator.geInstance().onJumpTo(RouteStatus.home);
        } else {
          print(result['msg']);
          showWarnToast(result['msg']);
        }
      } on NeedAuth catch (e) {
        print(e);
        showWarnToast(e.message);
      } on HiNetError catch (e) {
        print(e);
        showWarnToast(e.message);
      } catch (e) {
        print("登录其它err:$e");
      }
    }

    return Scaffold(
      appBar: appBar('登录', '注册', () {
        HiNavigator.geInstance().onJumpTo(RouteStatus.registration);
      }),
      body: Container(
        // listview包裹输入框 可以让键盘顶上去的时候 输入框不被遮盖
        child: ListView(
          children: [
            HLoginEffect(protect: protect.value),
            HLoginInput(
              '用户名',
              '请输入用户名',
              onChanged: (text) {
                data.value['userName'] = text;
                checkInput();
              },
            ),
            HLoginInput(
              '密码',
              '请输入密码',
              lineStretch: true,
              obscureText: true,
              onChanged: (text) {
                data.value['password'] = text;
                checkInput();
              },
              focusChanged: (val) {
                protect.value = val;
              },
            ),
            Padding(
              padding: EdgeInsets.only(top: 20, left: 20, right: 20),
              child: HLoginButton(
                '登录',
                enable: loginEnable.value,
                onPressed: send,
              ),
            )
          ],
        ),
      ),
    );
  }
}
